package com.example.beikeyigou;

import android.content.Intent;
import android.os.Bundle;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.beikeyigou.login_reg.UserBean;
import com.example.beikeyigou.pay.PayActivity;
import com.example.beikeyigou.trolley.TrolleyAdapter;
import com.example.beikeyigou.trolley.TrolleyBean;
import com.example.beikeyigou.utils.BaseFragment;
import com.example.beikeyigou.utils.SaveUserUtils;
import com.example.beikeyigou.utils.URLUtils;
import com.google.gson.Gson;

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * 购物车碎片
 */
public class TrolleyFragment extends BaseFragment {
    private ListView listView;
    private Button payBtn;
    private TextView totalPriceTv, numTv;
    private CheckBox selectAll;

    TrolleyAdapter adapter;
    List<TrolleyBean.DataBean> goodsData;
    UserBean.DataBean userData;
    List<Boolean> bList = new ArrayList<>();        // 记录购物车中商品的选中情况
    boolean bSelectAll = false;                     // 全选标志位
//    double totalPrice = 0;
    BigDecimal totalPriceBD = new BigDecimal("0");      // 使用double来计算金额会产生精度问题

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_trolley, container, false);

        findView(view);
        initData();
        setListener();
        return view;
    }

    private boolean isbSelect() {
        for (int i = 0; i < bList.size(); ++i) {
            if (bList.get(i)) {
                return true;
            }
        }
        return false;
    }

    private void setListener() {
        selectAll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                bSelectAll = !bSelectAll;
                int size = goodsData.size();
                if (bSelectAll) {
                    totalPriceBD = new BigDecimal("0");
                    for (int i = 0; i < size; ++i) {
                        bList.set(i, true);
                        totalPriceBD = totalPriceBD.add(new BigDecimal(String.valueOf(goodsData.get(i).getTotalprices())));
                        adapter.notifyDataSetChanged();
                    }
                    totalPriceTv.setText(String.valueOf("￥" + totalPriceBD.toString()));
                } else {
                    totalPriceBD = new BigDecimal("0");
                    for (int i = 0; i < size; ++i) {
                        bList.set(i, false);
                        adapter.notifyDataSetChanged();
                    }
                    totalPriceTv.setText(String.valueOf("￥" + totalPriceBD.toString()));
                }
            }
        });

        payBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (userData == null) {
                    Toast.makeText(getContext(), "请先登录", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (!isbSelect()) {
                    Toast.makeText(getContext(), "您还没选择宝贝哦~", Toast.LENGTH_SHORT).show();
                    return;
                }

                List<TrolleyBean.DataBean> goodsPay = new ArrayList<>();
                for (int i = 0; i < bList.size(); ++i) {
                    if (bList.get(i)) {
                        goodsPay.add(goodsData.get(i));
                    }
                }

                Intent intent = new Intent(getActivity(), PayActivity.class);
                Bundle bundle = new Bundle();
                bundle.putSerializable("trolleyData", (Serializable) goodsPay);
                intent.putExtras(bundle);
                intent.putExtra("flag", 2);
                startActivity(intent);

//                List<SelectGood> goodsPay = new ArrayList<>();
//                for (int i = 0; i < bList.size(); ++i) {
//                    if ((bList.get(i))) {
//                        goodsPay.add(new SelectGood(goodsData.get(i).getId(), userData.getId()
//                                , goodsData.get(i).getCommodityId()
//                                , goodsData.get(i).getCount()));
//                    }
//                }
//                String string = (new Gson()).toJson(goodsPay);
//                // 网络请求
//                RequestParams params = new RequestParams(URLUtils.orderShopping_url);
//                // 将提交的键值对放到请求参数中
//                params.setBodyContent(string);
//                params.setAsJsonContent(true);
//                params.setBodyContentType("application/json;charset=utf-8");
//
//                x.http().post(params, new Callback.CommonCallback<String>() {
//                    @Override
//                    public void onSuccess(String result) {
//                    }
//
//                    @Override
//                    public void onError(Throwable ex, boolean isOnCallback) {
//                        Toast.makeText(getContext(), "error", Toast.LENGTH_SHORT).show();
//                    }
//
//                    @Override
//                    public void onCancelled(CancelledException cex) {
//
//                    }
//
//                    @Override
//                    public void onFinished() {
//
//                    }
//                });
//                refreshData();
            }
        });
    }

    private void initData() {
        goodsData = new ArrayList<>();
//        listView.setAdapter(adapter);
        adapter = new TrolleyAdapter(getContext(), goodsData, bList)
                .setOnSelectListener(new TrolleyAdapter.OnSelectListener() {
                    @Override
                    public void onSelect(int pos, boolean status) {
                        List<Boolean> booleanList = adapter.getBList();
                        booleanList.set(pos, status);
                        int size = booleanList.size();
                        if (status) {
                            int i;
                            for (i = 0; i < size; ++i) {
                                if (!booleanList.get(i)) {
                                    break;
                                }
                            }
                            if (i == size) {
                                bSelectAll = true;
                                selectAll.setChecked(true);
                            }
                            totalPriceBD = totalPriceBD.add(new BigDecimal(String.valueOf(goodsData.get(pos).getTotalprices())));
                            totalPriceTv.setText("￥" + totalPriceBD.toString());
                        } else {
                            if (bSelectAll) {
                                bSelectAll = false;
                                selectAll.setChecked(false);
                            }
                            totalPriceBD = totalPriceBD.subtract(new BigDecimal(String.valueOf(goodsData.get(pos).getTotalprices())));
                            totalPriceTv.setText("￥" + totalPriceBD.toString());
                        }
                    }
                });
        listView.setAdapter(adapter);
        refreshData();
    }

    private void refreshData() {
        userData = SaveUserUtils.getUserData(getContext());
        if (userData == null) {
            totalPriceTv.setText("￥" + totalPriceBD.toString());
            numTv.setText("(0)");
            goodsData.clear();
            bList.clear();
            adapter.notifyDataSetChanged();
        } else {
            getNetwork(URLUtils.queryShoppingCar_url + "?userId=" + String.valueOf(userData.getId()));
        }
    }

    //点击上面的item切换下面的页面
//    private void refreshGoods () {
//        FragmentTransaction transaction = fm.beginTransaction();
//        TrolleyListFragment gtFrag = TrolleyListFragment.newInstance(goodsData);
//        transaction.replace(R.id.frag_trolley_goods, gtFrag);
//        transaction.commit();
//    }

    @Override
    public void onSuccess(String result) {
        super.onSuccess(result);
        TrolleyBean trolleyBean = new Gson().fromJson(result, TrolleyBean.class);    // 解析数据
        switch (trolleyBean.getCode()) {
            case 200:
                List<TrolleyBean.DataBean> list = trolleyBean.getData();                  // 获取网络数据集合
                goodsData.clear();
                goodsData.addAll(list);                  // 将网络数据添加到list view的数据源中
                bList.clear();
                for (int i = 0; i < goodsData.size(); ++i) {
                    bList.add(false);
                }
                adapter.notifyDataSetChanged();

                // 计算总价
                totalPriceBD = new BigDecimal("0");
                totalPriceTv.setText("￥" + totalPriceBD.toString());
                numTv.setText("(" + String.valueOf(goodsData.size()) + ")");

//                refreshGoods();
                break;
            case 201:
                goodsData.clear();
                bList.clear();
                adapter.notifyDataSetChanged();
                totalPriceBD = new BigDecimal("0");
                totalPriceTv.setText("￥" + totalPriceBD.toString());
                numTv.setText("(0)");
                break;
            default:
                Toast.makeText(getContext(), "购物车查询失败", Toast.LENGTH_SHORT).show();
                break;
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        refreshData();
    }

    private void findView(View view) {
        listView = view.findViewById(R.id.frag_trolley_listLv);
        totalPriceTv = view.findViewById(R.id.frag_trolley_all_price);
        numTv = view.findViewById(R.id.frag_trolley_num);
        selectAll = view.findViewById(R.id.frag_trolley_select_all);
        payBtn = view.findViewById(R.id.frag_trolley_btn);
    }
}